package com.wind.sqlite.tools;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.Random;

public class RandomStringGenerator {
    private static final String ALLOWED_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    public static String generateRandomString(int length) {
        Random random = new Random();
        StringBuilder builder = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(ALLOWED_CHARACTERS.length());
            char randomChar = ALLOWED_CHARACTERS.charAt(index);
            builder.append(randomChar);
        }
        return builder.toString();
    }


    public static int getFreePort()  {
        ServerSocket socket = null;
        try {
            socket = new ServerSocket(0); // 这里的参数设置为 0，表示让系统自动分配空闲端口号
        } catch (IOException e) {
           // throw new IOException("Failed to find a free port: " + e.getMessage());
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    // ignore
                }
            }
        }

        return socket.getLocalPort();
    }
}
